//
//  UploadImageController.swift
//  11111111
//
//  Created by cmh on 15/9/10.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit

// CELL标识
private let UploadImageCellID = "UploadImageCellID"

// 最大旋转图片数量
private let selectMaxPicture = 9

class UploadImageController: UICollectionViewController, UploadImageCellDelegate {
    
    // 定义数组保存添加的cell个数
    private lazy var pictures = [UIImage]()
    
    // 用户当前选中图片的索引
    private lazy var selectIndex = 0
    
    init() {
        let layout = UICollectionViewFlowLayout()
        
        super.init(collectionViewLayout: layout)
        
        layout.itemSize = CGSize(width: 80, height: 80)

        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

        // 注册cell
        self.collectionView!.registerClass(UploadImageCell.self, forCellWithReuseIdentifier: UploadImageCellID)

    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + ( pictures.count == selectMaxPicture ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(UploadImageCellID, forIndexPath: indexPath) as! UploadImageCell
        
        cell.UploadImageDelegate = self
    
        // 让最后一个cell显示添加按钮，别的显示添加的图片，因为这里的索引会比数据源多一个
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil

        return cell
    }
    
    // cell被点击的时候调用
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("无法访问相册")
            return
        }
        
        // 记录索引
        selectIndex = indexPath.item
        
        let vc = UIImagePickerController()
        
        // 监听照片选择
        vc.delegate = self
        
        presentViewController(vc, animated: true, completion: nil)
        
    }
    
    // 代理的实现
    private func UploadImageCellclickRemoveBtn(cell: UploadImageCell) {
        
        // 移除照片
        if let indexpath = collectionView?.indexPathForCell(cell) where indexpath.item < pictures.count {
        
            pictures.removeAtIndex(indexpath.item)
            
            collectionView?.reloadData()
        }
    }
    
}

// 相册的代理方法
extension UploadImageController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 对图片处理，按比例缩小图片的尺寸
       let newImage = image.scaleImageToWidth(300)
        
        // 用户选中了一张照片
        if selectIndex < pictures.count {
            pictures[selectIndex] = newImage
        } else {
            pictures.append(newImage)
        }
        
        // 刷新视图
        collectionView?.reloadData()
        
        // 关闭相册
        dismissViewControllerAnimated(true, completion: nil)

    }
}

// 定义代理协议
private protocol UploadImageCellDelegate: NSObjectProtocol {
    
    func UploadImageCellclickRemoveBtn(cell: UploadImageCell)
}

// 自定义cell
private class UploadImageCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet{
            
            if image != nil {
                iconView.image = image
                
            } else {
                iconView.image = UIImage(named: "compose_pic_add")
            }
            
            removeBtn.hidden = (image == nil)
        }
    }
    
    // 定义代理属性
    weak var UploadImageDelegate: UploadImageCellDelegate?
    
    // 删除按钮的点击
    @objc private func clickRemoveBtn() {
        
        UploadImageDelegate?.UploadImageCellclickRemoveBtn(self)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")

    }
    
    // 设置控件
    private func setupUI() {
        
        // 添加控件
        contentView.addSubview(iconView)
        contentView.addSubview(removeBtn)
        
        // 设置布局
        iconView.frame = bounds
        
        removeBtn.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["rv" : removeBtn]
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rv]-(0)-|", options: [], metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[rv]", options: [], metrics: nil, views: dict))
        
        // 移除按钮的点击方法
        removeBtn.addTarget(self, action: "clickRemoveBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置图片的填充样式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
    
    }

    // 懒加载控件
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "compose_pic_add"))
    
    
    private lazy var removeBtn: UIButton = UIButton(imageName: "compose_photo_close")

}
